package rpc;

import rpc.config.RegistryConfig;
import rpc.config.RpcConfig;
import rpc.registry.RegistryFactory;
import rpc.registry.Registry;
import rpc.utils.ConfigUtils;
import rpc.constant.RpcConstant;
import lombok.extern.slf4j.Slf4j;

//存放全局里用到的变量
@Slf4j//全局配置
public class RpcApplication {
    private static volatile RpcConfig rpcConfig;
    //框架初始化,支持传入自定义配置
    public static void init(RpcConfig newrpcConfig){
        rpcConfig=newrpcConfig;
        log.info("rpc init,config={}",newrpcConfig.toString());
        //注册中心初始化
        RegistryConfig registryConfig=rpcConfig.getRegistryConfig();
        Registry registry= RegistryFactory.getInstance();
        registry.init(registryConfig);
        log.info("registry init,config={}",registryConfig);
        //创建shutdown hook ,JVM虚拟机退出时执行操作
        Runtime.getRuntime().addShutdownHook(new Thread(registry::destroy));
    }
    //初始化
    public static void init(){
        RpcConfig newRpcConfig;
        try {
            newRpcConfig=ConfigUtils.loadConfig(RpcConfig.class,RpcConstant.DEFAULT_CONFIG_PREFIX);
        }catch (Exception e){
            //加载配置失败，使用默认值
            System.out.println("rpc init error");
            newRpcConfig=new RpcConfig();
        }
        init(newRpcConfig);
    }
    //获取配置
    public static RpcConfig getRpcConfig(){
        if(rpcConfig==null){
            synchronized (RpcApplication.class){
                if(rpcConfig==null){
                    init();
                }
            }
        }
        return rpcConfig;
    }
}
